<template>
    <!-- 预约页面 -->
    <div class="app-container">
        <div class="Information">
            <el-row>
                <el-form :model="form" label-width="65px">
                    <el-col :span="3">
                        <el-form-item label="姓名:">{{ form.student.name }} </el-form-item>
                    </el-col>
                    <el-col :span="2">
                        <el-form-item label="性别:">{{ form.student.sex == '0' ? '男' : '女' }} </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="">{{ form.student.deptNames }} {{ form.student.specialityName }}</el-form-item>
                    </el-col>

                    <el-col :span="4">
                        <el-form-item label="电话:">{{ form.student.mobile }} </el-form-item>
                    </el-col>
                    <el-col :span="3">
                        <el-form-item label="注册号:">{{ form.student.sno }} </el-form-item>
                    </el-col>
                </el-form>
            </el-row>
        </div>
        <div class="text-details">
            <h3>预约信息</h3>
            <el-form :model="ruleForm" ref="ruleForm" :rules="rules" label-width="100px" class="demo-ruleForm">
                <el-form-item label="预约咨询师" prop="pcbId">
                    <el-radio-group v-model="ruleForm.pcbId">
                        <el-radio v-for="(item, index) in consultantsList" :key="index" @change="changeRadio(item)"
                            :label="item.pcbId" :value="item.pcbId">{{ item.consName }}</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="预约时段" prop="aptStartEndTimeStr">
                    <el-date-picker v-model="ruleForm.aptStartEndTimeStr" type="date" value-format="yyyy-MM-dd"
                        format="yyyy-MM-dd" placeholder="选择日期" style="width: 30%;" @change="timeChange"
                        popper-class="picker-popper" :picker-options="pickerOptions">
                    </el-date-picker>
                    <el-radio-group v-model="ruleForm.data">
                        <el-radio v-for="(item, i) in timeRadio" :key="i" :label="item"
                            :disabled="(item.isApt == 1 || isaptTime == true) ? true : false">{{
                                item.startTime.substring(11,
                                    16)
                            }}~{{ item.endTime.substring(11, 16) }} {{ item.isApt == 1 ? '（已预约）' : '' }}</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="咨询诉求：" prop="consReqs">
                    <el-checkbox-group v-model="ruleForm.consReqs">
                        <el-checkbox v-for="dict in dict.type.psy_cons_req_type" :key="dict.value" :label="dict.value"
                            :value="dict.value">{{ dict.label }}</el-checkbox>
                    </el-checkbox-group>

                    <el-input type="textarea" maxlength="500" show-word-limit v-model="ruleForm.consReqCont" :autosize="{ minRows: 2, maxRows: 4}"></el-input>

                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="submitForm('ruleForm')">提交预约</el-button>
                    <el-button @click="resetForm('ruleForm')">重置</el-button>
                </el-form-item>
            </el-form>
        </div>

    </div>
</template>
    
<script>
import { addConsapt, consAllList } from '@/api/psychological/reservation'

export default {
    name: "Dict",
    dicts: ['psy_cons_req_type'],
    data() {
        return {
            ruleForm: {
                consReqs: [],
                pcbId: null,
                aptStartEndTimeStr: ''
            },
            form: {
                regCode: '',
                sex: '',
                mobile: '',
                studentName: ''
            },
            isaptTime: false,
            rules: {
                pcbId: [
                    { required: true, message: "请选择咨询师", trigger: "change" }
                ],
                aptStartEndTimeStr: [
                    { required: true, message: "请选择时间", trigger: "change" }
                ],
                consReqs: [
                    { required: true, message: "请选择咨询诉求", trigger: "change" }
                ],
                name: [
                    { required: true, message: "专业名称不能为空", trigger: "blur" }
                ],
            },
            timeList: [],
            timeRadio: [],
            consultantsList: [],
            timeaptDateList: [], //选择时间
            timeFies: false,
            pickerOptions: {
                cellClassName: (time) => {
                    if (this.timeList.includes(this.parseTime(time, '{y}-{m}-{d}'))) {
                        return 'badge'
                    }
                }
            }

        }
    },
    created() {
        consAllList().then(res => {
            this.consultantsList = res.data
        })

        this.form = this.$store.state.user.userInfor
        if (this.$store.state.user.userInfor.student) {
            this.form.student = this.$store.state.user.userInfor.student
        } else {
            this.form.student = {
                name: null,
                sex: null,
                deptNames: null,
                specialityName: null,
                mobile: null,
                sno: null

            }
        }
    },
    mounted() {
        this.Init()
    },
    methods: {
        Init() {
            // 对象赋值时 绑定对象中的属性不存在了 
            this.timeList = []
            if (this.$route.query.psyConsDateList) {

                console.log(this.$route.query,'this.$route.query')
                this.ruleForm.pcbId = Number(this.$route.query.pcbId)
                this.ruleForm.aptStartEndTimeStr = this.$route.query.psyConsDateList[0].pcdDate
                this.timeRadio = this.$route.query.psyConsDateList[0].psyConsTimeList
                this.$route.query.psyConsDateList.forEach(e => {
                    this.timeList.push(e.pcdDate)
                })
            }else {
                return
            }
        },
        parseTime(time, cFormat) {
            if (arguments.length === 0 || !time) {
                return null
            }
            const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
            let date
            if (typeof time === 'object') {
                date = time
            } else {
                if ((typeof time === 'string')) {
                    if ((/^[0-9]+$/.test(time))) {
                        time = parseInt(time)
                    } else {
                        time = time.replace(new RegExp(/-/gm), '/')
                    }
                }

                if ((typeof time === 'number') && (time.toString().length === 10)) {
                    time = time * 1000
                }
                date = new Date(time)
            }
            const formatObj = {
                y: date.getFullYear(),
                m: date.getMonth() + 1,
                d: date.getDate(),
                h: date.getHours(),
                i: date.getMinutes(),
                s: date.getSeconds(),
                a: date.getDay()
            }
            const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
                const value = formatObj[key]
                if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
                return value.toString().padStart(2, '0')
            })
            return time_str
        },
        changeRadio(data) {
            this.timeList = []
            console.log(data, 'data.psyConsDateList[0].psyConsTimeList')
            this.ruleForm.consName = data.consName
            if (data.psyConsDateList[0]) {
                this.timeRadio = data.psyConsDateList[0].psyConsTimeList
                let currentDate = new Date()
                this.timeRadio.forEach(item => {
                    if (currentDate > new Date(item.startTime)) {
                        console.log("当前时间晚于指定日期和时间");
                        this.isaptTime = true
                    } else {
                        this.isaptTime = false
                    }
                })
                data.psyConsDateList.forEach(e => {
                    this.timeList.push(e.pcdDate)
                })
                this.ruleForm.aptStartEndTimeStr = data.psyConsDateList[0].pcdDate
                console.log(data, this.timeRadio, this.timeList, this.ruleForm.aptStartEndTimeStr, '选择的咨询师')
                this.timeaptDateList = data.psyConsDateList
            } else {
                this.$modal.msgError("该咨询师没有可以预约的时间，请重新选择咨询师。");
                this.ruleForm.aptStartEndTimeStr = ''
                // this.timeaptDateList = []
                this.timeRadio = []
            }


        },
        timeChange(data) {
            this.timeFies = false
            console.log(this.timeList, data, this.timeFies, ' ')
            this.timeaptDateList.forEach(item => {
                console.log(item, data, 'sssssssssss')
                console.log(item.pcdDate === data, 'item.pcdDate === data')

                if (item.pcdDate === data) {

                    console.log(item, data, this.timeFies, '星图')
                    this.ruleForm.aptStartEndTimeStr = item.pcdDate
                    this.timeRadio = item.psyConsTimeList
                }
            })
            this.timeaptDateList
            const result = this.timeaptDateList.some(item => item.pcdDate === data);
            if (result == true) {
                this.timeFies = false
            } else {
                this.timeFies = true
            }
            console.log(result, this.timeFies, 'this.timeFies');
            let currentDate = new Date()
            this.timeRadio.forEach(item => {
                if (currentDate > new Date(item.startTime)) {
                    console.log("当前时间晚于指定日期和时间");
                    this.isaptTime = true
                } else {
                    this.isaptTime = false
                }
            })
            console.log(this.timeFies, '选择时间')
            if (this.timeFies === true) {
                this.$modal.msgError("选择的时间没有可以预约的时间请重新选择");
                this.ruleForm.aptStartEndTimeStr = ''
                this.timeRadio = []
            }
        },
        submitForm() {
            console.log(this.ruleForm)
            this.ruleForm.consReqs = this.ruleForm.consReqs.sort();
            if(this.ruleForm.data) {
                this.ruleForm.aptStartTime = this.ruleForm.data.startTime.substring(0, 16)
            this.ruleForm.aptEndTime = this.ruleForm.data.endTime.substring(0, 16)
            }else {
                this.$modal.msgWarning("请选择预约时间段");
            }
           
            console.log(this.ruleForm)

            this.$refs["ruleForm"].validate(valid => {
                if (valid) {

                    addConsapt(this.ruleForm).then(res => {
                        console.log(res, '预约成功')
                        if (res.code == 200) {
                            this.$modal.msgSuccess("预约成功");
                            this.$router.push({ path: '/psychological/successMack', query: this.ruleForm })
                        }
                    })

                }
            });
        },

    }
};
</script>
<style>
.picker-popper .el-date-table__row .badge::after {
    position: absolute;
    content: "";
    left: 17px;
    bottom: -3px;
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background-color: red;
}
</style>
<style scoped>
.Information {
    background-color: #EFEFEF;
    padding: 1% 2% 0 2%;
    margin-bottom: 2%;
}

.text-details {
    background-color: #EFEFEF;
    padding: 1% 2% 2% 2%;
    margin-bottom: 2%;
}
</style>
